#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
	vector<vector<int>> highestRankedKItems(vector<vector<int>>& grid, vector<int>& pricing, vector<int>& start, int k)
	{
		queue que { deque { pair { start[0], start[1] } } };
		int len_row = size(grid), len_col = size(grid[0]);
		array<int[2], 4> direction = { { { -1, 0 }, { 0, -1 }, { 0, 1 }, { 1, 0 } } };

		auto comp = [&grid, len_col](const pair<int, int>& o1, const pair<int, int>& o2) {
			return grid[o1.first][o1.second] < grid[o2.first][o2.second] ? true :
				o1.second + o1.first * len_col < o2.second + o2.first * len_col;
		};
		set<pair<int, int>, decltype(comp)> res_set(comp);
		vector<vector<int>> res;

		auto last = que.front();
		vector vis(len_row, vector(len_col, false)); vis[start[0]][start[1]] = true;
		while (!que.empty()) {
			auto [row, col] = que.front(); que.pop();
			res_set.emplace(row, col);
			for (auto [dx, dy] : direction) {
				int new_row = row + dx, new_col = col + dy;
				if (new_row < 0 || new_col < 0 || new_row == len_row || new_col == len_col ||
						vis[new_row][new_col] || grid[new_row][new_col] == 0) continue;
				que.emplace(new_row, new_col);
				vis[new_row][new_col] = true;
			}
			if (last == pair { row, col }) {
				for (auto [x, y] : res_set) {
					if (grid[x][y] != 1 && grid[x][y] >= pricing[0] && grid[x][y] <= pricing[1]) {
						if (k-- != 0) res.push_back({ x, y });
						else return res;
					}
				}
				res_set.clear();
				if (!que.empty()) last = que.back();
			}
		}
		return res;
	}

private:
};

int main()
{
	[[maybe_unused]] Solution solution;
	return 0;
}
